package com.doupi.partner.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;

/**
 * 生成UUID工具
 * 
 * @author Super Jens Wang
 * @version 1.0 $id: OrderIdUtils.java 2016年11月1日 下午4:56:33 Wang Le $
 */
public final class UUIDUtils {
	private final ThreadLocal<Integer> seed = new ThreadLocal<>();
	private static final UUIDUtils INSTANCE = new UUIDUtils();
	private static final String RANDOM_STRING = "ABCDEFGHJKLMNPQRSTUVYXWZ";
	private static final String INIT_UUID_DATE_FORMAT = "yyMMddHHmmssSSS";
	private static final String DEFAULT_PAD_STRING = "0";
	private static final int DEFAULT_UUID_LENGTH = 16;

	private UUIDUtils() {
	}

	/**
	 * 生成DEFUALT_UUID_LENGTH的基础上，后尾补齐tailLength长度的uuid
	 * 
	 * @param tailLength
	 *            后尾补齐的长度
	 * 
	 * @param padString
	 *            后补齐字符
	 */
	private String generator(int tailLength, String padString) {
		StringBuffer dateFormatString = new StringBuffer(DateFormatUtils.format(new Date(), INIT_UUID_DATE_FORMAT));
		if (tailLength > 0) {
			synchronized (this.seed) {
				if (null == seed.get() || seed.get() > Math.pow(10, tailLength) - 1) {
					seed.set(1);
				}
				int currenSeed = seed.get();
				dateFormatString = dateFormatString.append(StringUtils.leftPad(String.valueOf(currenSeed), tailLength, padString));
				seed.set(currenSeed + 1);
			}
		}
		dateFormatString = dateFormatString.insert(0, RandomStringUtils.random(1, RANDOM_STRING));
		return dateFormatString.toString();
	}

	/**
	 * 返回默认随机一个字母+默认日期格式的DEFUALT_UUID_LENGTH位字符
	 * 
	 * <pre>
	 *     如：
	 * </pre>
	 *
	 **/
	public static String uuid() {
		return INSTANCE.generator(0, DEFAULT_PAD_STRING);
	}

	/**
	 * 返回在默认uuid的基础上的长度的uuid 
	 * 
	 * @param length
	 *            - uuid长度
	 */
	public static String uuid(int length) {
		if (length < DEFAULT_UUID_LENGTH) {
			return uuid();
		}
		return INSTANCE.generator(length - DEFAULT_UUID_LENGTH, DEFAULT_PAD_STRING);
	}

	/**
	 * 
	 * @param padString
	 *            补充字符
	 */
	public static String uuid(String padString) {
		return INSTANCE.generator(0, padString);
	}

	/**
	 * 
	 * @param length
	 *            长度
	 * @param padString
	 *            补齐字符
	 */
	public static String uuid(int length, String padString) {
		if (length < DEFAULT_UUID_LENGTH) {
			length = DEFAULT_UUID_LENGTH;
		}
		return INSTANCE.generator(length - DEFAULT_UUID_LENGTH, padString);
	}
}
